package raochang.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import raochang.mapper.ReaderMapper;
import raochang.pojo.entry.Reader;
import raochang.pojo.vo.ReadsResponseVo;
import raochang.pojo.vo.ReaderVo;
import raochang.service.ReadersService;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <p>
 * 读者管理-目前按照班级 服务实现类
 * </p>
 *
 * @author itheima
 */

@Service
public class ReadersServiceImpl extends ServiceImpl<ReaderMapper, Reader> implements ReadersService {
    private static final String USER_AGENT = "Mozilla/5.0";
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importReads(String session) {
        String url = "https://lib.scjyzb.cn/v1/bookReader/findReaderList?page=1&pagesize=100";
        try {
            System.out.println("开始导入读者数据---------");
            sendPOST(url,session);
            System.out.println("导入读者数据成功---------");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("导入读者数据失败---------");
        }
    }
    private void sendPOST(String url,String session) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", USER_AGENT);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Connection", "keep-alive");
//        httpPost.setHeader("Content-Length", "2");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Cookie", "orgType=2; orgId=08534; SESSION="+session+"; SF_cookie_11=78087231; menuUrl=/winshare-library/school/library/org_list");
        httpPost.setHeader("Host", "lib.scjyzb.net");
        httpPost.setHeader("Origin", "https://lib.scjyzb.net");
        httpPost.setHeader("Referer", "https://lib.scjyzb.net/");
        httpPost.setHeader("sec-ch-ua", "\";Not A Brand\";v=\"99\", \"Chromium\";v=\"94\"");
        httpPost.setHeader("sec-ch-ua-mobile", "?0");
        httpPost.setHeader("sec-ch-ua-platform", "Windows");
        httpPost.setHeader("Sec-Fetch-Dest", "empty");
        httpPost.setHeader("Sec-Fetch-Mode", "cors");
        httpPost.setHeader("Sec-Fetch-Site", "same-origin");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        //直接写死没关系，查询班级和正常状态的读者
        String jsonPayload = "{\"depotId\": \"336514\",\"depotName\": \"336514\", \"state\": \"0\"}";
        HttpEntity entity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("Response Code: " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        importToDb(response);
    }

    private  void importToDb(StringBuffer response) {
        /**
         * 数据转换成接受类
         */
        Gson gson = new Gson();
        ReadsResponseVo person = gson.fromJson(response.toString(), ReadsResponseVo.class);
        List<ReaderVo> rows = person.getRows();
        //判断集合是否为空
        if (!CollectionUtils.isEmpty(rows)) {
            rows.forEach(s->{
                Reader reader = new Reader();
                reader.setReaderName(s.getName());
                reader.setReaderCode(s.getUserCode());
                reader.setReaderId(s.getId());
               save(reader);
            });
        }
    }
}
